package net.maku.monitor.controller;

import net.maku.framework.common.cache.LocalCache;
import net.maku.framework.common.utils.Result;
import net.maku.monitor.vo.Cache;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import jakarta.annotation.Resource;
import java.util.*;

@RestController
@RequestMapping("monitor/cache")
public class CacheController {

    @Resource
    private LocalCache localCache;

    /**
     * 获取本地缓存详情
     */
    @GetMapping("info")
    @PreAuthorize("hasAuthority('monitor:cache:all')")
    public Result<Map<String, Object>> getInfo() {
        Map<String, Object> result = new HashMap<>();
        // 获取缓存信息（这里只能根据本地缓存的实现来获取）
        result.put("cacheSize", localCache.getCacheSize());  // 例如获取缓存的大小
        return Result.ok(result);
    }

    /**
     * 获取所有的Key
     */
    @GetMapping("getCacheKeys")
    @PreAuthorize("hasAuthority('monitor:cache:all')")
    public Result<Set<String>> getCacheKeys() {
        Set<String> cacheKeys = localCache.keys("*");  // 查找本地缓存的所有键
        return Result.ok(cacheKeys);
    }

    /**
     * 获取结构化键下的Key值
     *
     * @param cacheKey
     */
    @GetMapping("getCacheKeys/{cacheKey}")
    @PreAuthorize("hasAuthority('monitor:cache:all')")
    public Result<Set<String>> getCacheKeys(@PathVariable String cacheKey) {
        Set<String> cacheKeys = localCache.keys(cacheKey + "*");  // 查找结构化缓存的键
        return Result.ok(cacheKeys);
    }

    /**
     * 获取指定键的值
     *
     * @param cacheKey
     */
    @GetMapping("getCacheValue/{cacheKey}")
    @PreAuthorize("hasAuthority('monitor:server:all')")
    public Result<Cache> getCacheValue(@PathVariable String cacheKey) {
        Object cacheValue = localCache.get(cacheKey);  // 获取本地缓存的值
        Cache cache = new Cache(cacheKey, cacheValue);
        return Result.ok(cache);
    }

    /**
     * 删除指定键的缓存
     *
     * @param cacheKey > Key值
     */
    @DeleteMapping("delCacheKey/{cacheKey}")
    @PreAuthorize("hasAuthority('monitor:cache:all')")
    public Result<String> delCacheKey(@PathVariable String cacheKey) {
        localCache.delete(cacheKey);  // 删除指定缓存
        return Result.ok();
    }

    /**
     * 删除结构化键下的缓存
     *
     * @param cacheKey > Key值
     */
    @DeleteMapping("delCacheKeys/{cacheKey}")
    @PreAuthorize("hasAuthority('monitor:cache:all')")
    public Result<String> delCacheKeys(@PathVariable String cacheKey) {
        Set<String> cacheKeys = localCache.keys(cacheKey + "*");
        localCache.delete(cacheKeys);  // 删除结构化键下的所有缓存
        return Result.ok();
    }

    /**
     * 删除全部缓存
     */
    @DeleteMapping("delCacheAll")
    @PreAuthorize("hasAuthority('monitor:cache:all')")
    public Result<String> delCacheAll() {
        Set<String> cacheKeys = localCache.keys("*");
        localCache.delete(cacheKeys);  // 删除所有缓存
        return Result.ok();
    }
}
